﻿using G3WebERPApi.Common;
using G3WebERPApi.Model;
using G3WebERPApi.Travel;
using G3WebERPApi.user;
using Newtonsoft.Json;
using System;
using System.Data;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;

namespace G3WebERPApi.Approval
{
    /// <summary>
    /// 出纳将已走完流程的单据进行付款操作
    /// </summary>
    public class CashierPay : IHttpHandler
    {
        
        private string ProName = "EXPEACCOUNTdd";//存储过程名

        public void ProcessRequest(HttpContext context)
        {
            //判断客户端请求是否为post方法
            if (context.Request.HttpMethod.ToUpper() != "POST")
            {
                context.Response.Write(JsonConvert.SerializeObject(new CommonModel { errcode = "-1", errmsg = "请使用POST方式" }));
                return;
            }
            //数据库链接
           
            string signUrl = ToolsClass.GetConfig("signUrl"); context.Response.ContentType = "text/plain";
            string CsJson;
            //获取请求json
            using (var reader = new StreamReader(context.Request.InputStream, Encoding.UTF8))
            {
                CsJson = reader.ReadToEnd();
            }

            string result;
            if (CsJson == "")
            {
                context.Response.Write(JsonConvert.SerializeObject(new CommonModel
                {
                    errcode = "1",
                    errmsg = "报文格式错误!"
                }));
                return;
            }
            CsJson = Regex.Replace(CsJson, @"[\n\r]", "").Replace(@"\n", ",").Replace("'", "‘").Replace(@"\t", ":").Replace(@"\r", ",").Replace(@"\n", ",");
            //#微应用ID:agentId #企业ID:corpId #应用的唯一标识:appKey #应用的密钥:appSecret
            string AppWyy = ToolsClass.GetConfig("AppWyy");
            string[] ScList = AppWyy.Split('$');
            string agentId = ScList[0].ToString();
            string appKey = ScList[2].ToString();
            string appSecret = ScList[3].ToString();

            string ddUrl = ToolsClass.GetConfig("ddUrl");
            ToolsClass.TxtLog("单据付款日志", $"\r\n单据付款入参:{CsJson}\r\n");
            //前端传入数据
            CashierPayModel payModel = (CashierPayModel)JsonConvert.DeserializeObject(CsJson, typeof(CashierPayModel));
            string path = context.Request.Path.Replace("Approval/CashierPay.ashx", "cashierpay");
            //验证请求sign
            string sign = ToolsClass.md5(signUrl + path + "Romens1/DingDing2" + path, 32);
            if (sign != payModel.Sign)
            {
                context.Response.Write(JsonConvert.SerializeObject(new CommonModel { errcode = "-1", errmsg = "认证信息Sign不存在或者不正确" }));
                return;
            }

            try
            {
                #region 获取access_token

                string url = "https://oapi.dingtalk.com/gettoken?appkey=" + appKey + "&appsecret=" + appSecret;
                string FhJson = ToolsClass.ApiFun("GET", url, "");

                CommonModel tokenClass = new CommonModel();
                tokenClass = (CommonModel)JsonConvert.DeserializeObject(FhJson, typeof(CommonModel));
                string access_token = tokenClass.access_token;
                if (tokenClass.errcode != "0")
                {
                    context.Response.Write(JsonConvert.SerializeObject(new CommonModel { errcode = "-1", errmsg = "获取ACCESS_TOKEN报错" }));
                    return;
                }

                #endregion 获取access_token

                #region 获取用户详情

                url = "https://oapi.dingtalk.com/user/get?access_token=" + access_token + "&userid=" + payModel.DDOperatorId;
                FhJson = ToolsClass.ApiFun("GET", url, "");

                GetUserXq userXqClass = new GetUserXq();
                userXqClass = (GetUserXq)JsonConvert.DeserializeObject(FhJson, typeof(GetUserXq));
                if (userXqClass.errcode != 0)
                {
                    context.Response.Write(JsonConvert.SerializeObject(new CommonModel { errcode = "-1", errmsg = "获取审批人详细信息报错" }));
                    return;
                }

                #endregion 获取用户详情

                #region 获取用户guid

                string Sql = $"select GUID from  operators  where code = '{userXqClass.jobnumber}'";
                var operatorDt = StaticDbHelper.GetSqlHelper().GetDataTable(Sql);
                if (operatorDt.Rows.Count == 0)
                {
                    context.Response.Write(JsonConvert.SerializeObject(new CommonModel { errcode = "-1", errmsg = "用户不存在" }));
                    return;
                }
                var operatorGuid = operatorDt.Rows[0].DataRowGetStringValue("GUID");
                #endregion 获取用户guid

                CommonModel xxtzClass2 = new CommonModel();
                StringBuilder piddept = new StringBuilder();
                string sql = string.Empty;
                string uiPro = string.Empty;
                DataTable logComments = new DataTable();
                StringBuilder logcoments = new StringBuilder();
                string billTypeNo = string.Empty;
                switch (payModel.FeeType)
                {
                    case "00":
                        uiPro = "/zdfui";
                        billTypeNo = "100520005010";
                        break;

                    case "01":
                        uiPro = "/jtfui";
                        billTypeNo = "100520005015";
                        break;

                    case "02":
                        uiPro = "/txfui";
                        billTypeNo = "100520005020";
                        break;

                    case "12":
                        uiPro = "/clfui";
                        billTypeNo = "100520005005";
                        break;

                    case "07":
                        uiPro = "/qtfyui";
                        billTypeNo = "100520005055";
                        break;

                    default:
                        break;
                }

                //获取当前单号的发起人和待报销人
                string billno = payModel.BillNo;
                var keyValuePairs = CommonHelper.sqlPro(billno, billTypeNo, operatorGuid, ProName);
                if (keyValuePairs["ReturnValue"].ToString() != "0")
                {
                    ToolsClass.TxtLog("单据付款日志", "\r\n调用存储过程失败:" + keyValuePairs["ReturnMsg"].ToString() + "\r\n");
                    context.Response.Write(JsonConvert.SerializeObject(new CommonModel { errcode = "-1", errmsg = keyValuePairs["ReturnMsg"].ToString() }));
                    return;
                }
                string urlcsjson = ddUrl + $"{uiPro}/shenpi/index.html?billno={payModel.BillNo}&BillClassId={payModel.BillClassId}&showmenu=false";
                urlcsjson = HttpUtility.UrlEncode(urlcsjson, Encoding.UTF8);
                DDMsgModel dDMsgModel = new DDMsgModel
                {
                    agent_id = agentId,
                    userid_list = payModel.DDOperatorId + "," + payModel.DDPayId,
                    msg = new DDMsgModelLinkMsg
                    {
                        msgtype = "link",
                        link = new DDMsgModelLink
                        {
                            messageUrl = $"dingtalk://dingtalkclient/page/link?url={urlcsjson}&pc_slide=true",
                            picUrl = "@",
                            text = $"单据{payModel.BillNo}已付款",
                            title = $"已付款{payModel.OperatorName}"
                        }
                    }
                };

                string ddjsonmsgModel = JsonConvert.SerializeObject(dDMsgModel);
                url = "https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2?access_token=" + access_token;
                FhJson = ToolsClass.ApiFun("POST", url, ddjsonmsgModel);
                ToolsClass.TxtLog("单据付款日志", "\r\n发送通知调用钉钉api入参:" + ddjsonmsgModel + "\r\n出参：" + FhJson);
                xxtzClass2 = (CommonModel)JsonConvert.DeserializeObject(FhJson, typeof(CommonModel));
                if (xxtzClass2.errcode != "0")
                {
                    switch (payModel.FeeType)
                    {
                        case "00":
                            StaticDbHelper.GetSqlHelper().ExecSql($"update EXPEENTEMENT set ISACCOUNT=0,ACCOUNTGUID='',ACCOUNTDate=null where BillNo = '{billno}' ");
                            break;

                        case "12":
                            StaticDbHelper.GetSqlHelper().ExecSql($"update ExpeTrav set ISACCOUNT=0,ACCOUNTGUID='',ACCOUNTDate=null where BillNo = '{billno}' ");
                            break;

                        default:
                            StaticDbHelper.GetSqlHelper().ExecSql($"update ExpeOther set ISACCOUNT=0,ACCOUNTGUID='',ACCOUNTDate=null where BillNo = '{billno}' ");
                            break;
                    }
                    context.Response.Write("{\"errmsg\":\"您的单据付款消息通知失败(DD6004)\",\"errcode\":1}");
                    return;
                }
                result = JsonConvert.SerializeObject(new ResultGetMulParams { errcode = "0", errmsg = "", NextUrl = "" });
                ToolsClass.TxtLog("单据付款日志", "\r\n返回前端信息:" + result + "\r\n");
                context.Response.Write(result);
                return;
            }
            catch (Exception ex)
            {
                context.Response.Write(JsonConvert.SerializeObject(new CommonModel { errcode = "-1", errmsg = "内部服务器错误" }));
                ToolsClass.TxtLog("单据付款异常", "\r\n:" + JsonConvert.SerializeObject(ex) + "\r\n");
                context.Response.End();
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}